package com.itmuch.box.core.freemarker;

import java.util.Arrays;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.itmuch.box.freemarker.directive.ContentListDirective;
import com.itmuch.box.freemarker.directive.ContentListPageDirective;

import freemarker.template.TemplateModelException;

public class ClassPathTldsLoader {
    private static final String SECURITY_TLD = "/META-INF/security.tld";

    final private List<String> classPathTlds;

    public ClassPathTldsLoader(String... classPathTlds) {
        super();
        if (ArrayUtils.isEmpty(classPathTlds)) {
            this.classPathTlds = Arrays.asList(SECURITY_TLD);
        } else {
            this.classPathTlds = Arrays.asList(classPathTlds);
        }
    }

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Autowired
    private freemarker.template.Configuration configuration;

    @Value("${adminPath}")
    private String adminPath;
    @Value("${commonPath}")
    private String commonPath;
    @Autowired
    private ContentListDirective contentListDirective;
    @Autowired
    private ContentListPageDirective contentListPageDirective;

    @PostConstruct
    public void loadClassPathTlds() throws TemplateModelException {
        this.configuration.setSharedVariable("adminPath", this.adminPath);
        this.configuration.setSharedVariable("commonPath", this.commonPath);

        // 自定义指令开始
        this.configuration.setSharedVariable("content_list", this.contentListDirective);
        this.configuration.setSharedVariable("content_list_page", this.contentListPageDirective);

        this.freeMarkerConfigurer.getTaglibFactory().setClasspathTlds(this.classPathTlds);
    }

}
